package cn.yitun.chat.yitunservermanagecore.general.manage.system.service.impl;

import cn.yitun.chat.yitunservercommonlib.dataentity.po.system.UserRoleInfo;
import cn.yitun.chat.yitunservercommonlib.util.R;
import cn.yitun.chat.yitunserverimbase.dao.system.UserRoleDao;
import cn.yitun.chat.yitunservermanagecore.general.manage.system.service.UserRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 
 * date 2018-07-17 22:39:50<br>
 * description
 * 
 * @author yitun<br>
 * @since
 */
@Service
@Transactional
public class UserRoleServiceImpl implements UserRoleService {

	@Resource
	UserRoleDao userRoleDAO;
	@Override
	public void addOrUpdate(Long userId, List<Long> roleIds) {
		List<UserRoleInfo> rmList = userRoleDAO.list(R.param("userId", userId));

		List<UserRoleInfo> deleteList = new ArrayList<>();

		Map<Long, UserRoleInfo> map = new HashMap<>();
		for (UserRoleInfo ur : rmList) {
			if (map.containsKey(ur.getRoleId())) {
				deleteList.add(ur);
			}
			map.put(ur.getRoleId(), ur);
		}

		List<UserRoleInfo> addList = new ArrayList<>();
		for (Long roleId : roleIds) {
			UserRoleInfo rm = map.remove(roleId);
			if (null == rm) {
				rm = new UserRoleInfo();
				rm.setRoleId(roleId);
				rm.setUserId(userId);
				addList.add(rm);
			}
		}
		deleteList.addAll(map.values());
		if (!addList.isEmpty()) {
			for (UserRoleInfo ur : addList) {
				userRoleDAO.save(ur);
			}
		}

		if (!deleteList.isEmpty()) {
			for (UserRoleInfo ur : deleteList) {
				userRoleDAO.remove(ur.getId());
			}
		}
	}

	/**
	 * 获取系统用户的角色列表 date 2018-07-18 09:29:20<br>
	 * description
	 * 
	 * @author yitun<br>
	 * @param userId
	 * @return
	 * @since
	 */
	@Override
	public List<UserRoleInfo> getUserRoleInfoListByUserId(Long userId) {
		List<Long> userIdList = new ArrayList<>();
		userIdList.add(userId);
		List<UserRoleInfo> urs = userRoleDAO.getListByUserIdList(userIdList);
		return urs;
	}
}
